import { createSlice } from "@reduxjs/toolkit";
const cratStore = createSlice({
  name: "cratStore",
  initialState: {
    cart: [] as any[],
  },
  reducers: {
    setCart: (state, action) => {
      state.cart = action.payload;
    },
    // 添加商品到购物车
    addGoods: (state, action) => {
      // 判断商品是否已经在购物车中
      const index = state.cart.findIndex(
        (item) => item.id === action.payload.id
      );
      if (index !== -1) {
        state.cart[index].quantity += 1;
      } else {
        state.cart.push({ ...action.payload, quantity: 1 });
      }
    },

    // 从购物车中移除商品
    removeGoods: (state, action) => {
      state.cart = state.cart.filter((item) => item.gameId !== action.payload);
    },

    // 修改商品数量
    changeGoodsNum: (state, action) => {
      const index = state.cart.findIndex(
        (item) => item.gameId === action.payload.gameId
      );
      if (index !== -1) {
        state.cart[index].quantity = action.payload.quantity;
      }
    },

    // 清空购物车
    clearGoods: (state) => {
      state.cart = [];
    },
  },
});

export const { addGoods, removeGoods, changeGoodsNum, clearGoods, setCart } =
  cratStore.actions;

export default cratStore.reducer;
